import { ForbiddenException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { hash, verify } from 'argon2';
import { PrismaService } from 'src/prisma/prisma.service';
import { LoginDto } from './dto/LoginDto';
import { RegisterDto } from './dto/RegisterDto';

@Injectable()
export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwtService: JwtService,
  ) {}

  async login({ name, password }: LoginDto) {
    const user = await this.prisma.user.findUnique({ where: { name } });

    if (!user) throw new ForbiddenException('用户不存在');

    if (!(await verify(user.password, password)))
      throw new ForbiddenException('密码输入错误');

    return {
      token: await this.jwtService.signAsync({
        username: user.name,
        sub: user.id,
      }),
    };
  }

  async register(registerDto: RegisterDto) {
    return await this.prisma.user.create({
      data: {
        name: registerDto.name,
        email: registerDto.email,
        password: await hash(registerDto.password),
      },
    });
  }
}
